package com.bw.module_live.anchor


import android.util.Log
import android.view.View
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.alibaba.android.arouter.facade.annotation.Route
import com.bw.lib_common.base.BaseMVIActivity
import com.bw.lib_common.utils.setLoginSingClick
import com.bw.lib_common.utils.setSingClick
import com.bw.lib_common.websocket.WebSocketUtils
import com.bw.lib_storage.UserMMKV
import com.bw.module_live.R
import com.bw.module_live.anchor.intent.LiveAnchorIntent
import com.bw.module_live.anchor.model.entity.CreateLiveRequestEntity
import com.bw.module_live.anchor.model.entity.SendRedPacketRequestEntity
import com.bw.module_live.anchor.state.CreateLiveState
import com.bw.module_live.anchor.state.SendGoodsAddState
import com.bw.module_live.anchor.state.SendGoodsRemovedState
import com.bw.module_live.anchor.state.SendRedPacketState
import com.bw.module_live.anchor.viewmodel.CreateLiveViewModel
import com.bw.module_live.databinding.ActivityCreateLiveBinding
import com.bw.module_live.fans.LiveActivity.Companion.TAG
import com.bw.module_live.im.LiveIM
import com.bw.module_live.im.MessageListener
import com.tencent.imsdk.v2.V2TIMAdvancedMsgListener
import com.tencent.imsdk.v2.V2TIMCallback
import com.tencent.imsdk.v2.V2TIMManager
import com.tencent.imsdk.v2.V2TIMMessage
import com.tencent.imsdk.v2.V2TIMValueCallback
import com.tencent.live2.V2TXLiveCode
import com.tencent.live2.V2TXLiveDef
import com.tencent.live2.V2TXLivePusher
import com.tencent.live2.impl.V2TXLivePusherImpl
import com.tencent.rtmp.ui.TXCloudVideoView
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import org.java_websocket.handshake.ServerHandshake
import org.json.JSONObject

/**
 * 0.接入im，创建聊天室---》roomId
 * 1.创建直播间(roomId，基本信息)----》服务器获得推流地址
 * 2.接入腾讯云推流
 * 3.推流成功：直播间页面；推流失败：创建直播间失败
 *
 *
 */
@AndroidEntryPoint
@Route(path = "/module_live/CreateLiveActivity")
class CreateLiveActivity : BaseMVIActivity() {
    private lateinit var mViewModel: CreateLiveViewModel
    private var roomId:String = ""
    private lateinit var webSocketUtils: WebSocketUtils
    private val mBinding : ActivityCreateLiveBinding by lazy  {
        ActivityCreateLiveBinding.inflate(layoutInflater)
    }
    private lateinit var mPusher:V2TXLivePusher
    override fun generateViewModel() {
        mViewModel = ViewModelProvider(this)[CreateLiveViewModel::class.java]
    }

    override fun getLayoutRootView(): View {
        return mBinding.root
    }

    override fun initView() {
        super.initView()
        //模拟登录，应该主页面做im登录
        LiveIM.loginIM()
        //推流组件
        mPusher = V2TXLivePusherImpl(this, V2TXLiveDef.V2TXLiveMode.TXLiveMode_RTMP)
        //预览
        mPusher.setRenderView(mBinding.pusherTxCloudView)
        mPusher.startCamera(true)
        mPusher.startMicrophone()
    }
    private fun initWebSocket(){
        webSocketUtils = WebSocketUtils.Builder()
            .setUri("ws://10.161.9.80:7037/liveRoom/websocket/$roomId/${UserMMKV.userId}")
            .setReceiveMessageListener(object : WebSocketUtils.ReceiveMessageListener{
                override fun onMessage(message: String?) {
                    if (message?.contains("heart") == false){
                        Log.d(TAG, "接收到消息: $message")
                        handleWebSocketMessage(message)
                    }
                }

                override fun onOpen(shake: ServerHandshake?) {
                    Log.d(TAG,"打开链接")

                }

                override fun onClose(code: Int, reason: String?, remote: Boolean) {
                    Log.d(TAG, "断开链接: ")

                }

                override fun onError(ex: Exception?) {
                    Log.d(TAG, "链接错误:")

                }
            }).build()
    }
    /**
     * 处理websocket消息
     * 0：链接成功
     * 1：红包消息{"type":1,"data":{"id":565,"room_id":"10456123","count":1,"money":10.0,"time":60000,"createTime":"Oct 27, 2025, 4:06:16 PM","status":1}}
     * 3：中将名单{"type":3,"data":{"id":565,"room_id":"10456123","count":1,"money":10.0,"time":60000,"createTime":"Oct 27, 2025, 4:06:16 PM","users":"[]","win_users":"[]","status":1}}
    9:上车：{"type":9,"data":"586148"}
    10：下车 {"type":10,"data":"586148"}
     */
    private fun handleWebSocketMessage(message: String) {

        val jsonObject = JSONObject(message)
        val type = jsonObject.getInt("type")
        when(type){
            0 -> {
                showMsg("链接成功")
            }
            1 -> {
                showMsg("有新红包消息")

            }
            3 ->{
                showMsg("中将名单")

            }
            5 -> {
                showMsg("有人加入")
            }
            9 -> {
                showMsg("上车") //更新recyclerview小黄车数据
            }
            10 -> {
                showMsg("下车") //更新recyclerview小黄车数据
            }
        }

    }
    override fun initEvent() {
        super.initEvent()

        mBinding.btCreateLive.setLoginSingClick {
            //创建群组
            V2TIMManager.getInstance().createGroup(V2TIMManager.GROUP_TYPE_AVCHATROOM, null, "xx的直播间",object : V2TIMValueCallback<String>{
                override fun onSuccess(p0: String) {
                    Log.d(TAG, "创建群组成功: $p0")
                    roomId = p0 //群组id
                    //发送意图创建直播间
                    lifecycleScope.launch {
                        repeatOnLifecycle(Lifecycle.State.RESUMED){
                            //接入im创建群组，群组发送给服务器
                            val createLiveRequestEntity = CreateLiveRequestEntity(room_description = "双十一",  room_id = roomId ,room_name = "xx的直播间")
                            mViewModel.intents.send(LiveAnchorIntent.CreateLive(createLiveRequestEntity))

                        }
                    }

                }

                override fun onError(p0: Int, p1: String?) {
                    Log.d(TAG, "创建群组失败: $p1")
                }

            })
        }
        //发红包
        mBinding.btSendRedPacket.setSingClick {
            lifecycleScope.launch {
                repeatOnLifecycle(Lifecycle.State.RESUMED){
                    /**
                     * {
                     *   "count": 0,
                     *   "money": 0,
                     *   "room_id": "",
                     *   "time": 0
                     * }
                     */
                    val sendRedPacketRequestEntity = SendRedPacketRequestEntity(count = 1 , money = 10, room_id = "10456123", time = 60 * 1000)
                    mViewModel.intents.send(LiveAnchorIntent.SendRedPacket(sendRedPacketRequestEntity))
                }
            }
        }
        //上车
        mBinding.btAddCar.setSingClick {
            lifecycleScope.launch {
                repeatOnLifecycle(Lifecycle.State.RESUMED){
                    mViewModel.intents.send(LiveAnchorIntent.SendGoods(mBinding.etGoodsId.text.toString(),roomId))
                }
            }
        }
        //下车
        mBinding.btRemoveCar.setSingClick {
            lifecycleScope.launch {
                repeatOnLifecycle(Lifecycle.State.RESUMED){
                    mViewModel.intents.send(LiveAnchorIntent.SendGoodsRemove(mBinding.etGoodsId.text.toString(),roomId))
                }
            }
        }
    }

    private val messageListener = MessageListener()
    /**
     * 处理状态，展示不同的ui
     */

    override fun handleState() {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED){
                mViewModel.createLiveState_.collect{
                    when(it){
                        is CreateLiveState.Loading -> {

                        }
                        is CreateLiveState.Success -> {
                            showMsg(it.entity.toString())
                            //推流
                            startPush(it.entity.push_url)
                            //加入群组
                            V2TIMManager.getInstance().joinGroup(roomId,"",object : V2TIMCallback {
                                override fun onSuccess() {
                                    Log.d(TAG, "加入成功: ")
                                    //监听器接受消息
                                    V2TIMManager.getMessageManager().addAdvancedMsgListener(messageListener)
                                }

                                override fun onError(p0: Int, p1: String?) {
                                    Log.d(TAG, "加入失败: ")
                                }
                            })

                        }
                        is CreateLiveState.Error -> {

                        }
                        is CreateLiveState.Init -> {

                        }
                    }
                }

            }
        }
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED){
                mViewModel.sendRedPacketState_.collect{
                    when(it){
                        is SendRedPacketState.Init -> {

                        }
                        is SendRedPacketState.Success -> {
                            showMsg("发送红包成功")
                        }
                        is SendRedPacketState.Error -> {
                            showMsg("发送红包失败")
                        }
                    }
                }
            }
        }
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED){
                mViewModel.sendGoodsAddState_.collect{
                    when(it){
                        is SendGoodsAddState.Init -> {

                        }
                        is SendGoodsAddState.Success -> {
                            showMsg("上车成功")
                        }
                        is SendGoodsAddState.Error -> {
                            showMsg("上车失败")
                        }
                    }
                }
            }
        }
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED){
                mViewModel.sendGoodsRemoveState_.collect{
                    when(it){
                        is SendGoodsRemovedState.Init -> {

                        }
                        is SendGoodsRemovedState.Success -> {
                            showMsg("下车成功")
                        }
                        is SendGoodsRemovedState.Error -> {
                            showMsg("下车失败")
                        }
                    }
                }
            }
        }

    }

    /**
     * 开始推流
     */
    private fun startPush(url:String){
        val result =  mPusher.startPush(url)
        if (result == V2TXLiveCode.V2TXLIVE_ERROR_INVALID_LICENSE){
            Log.d("TAG", "推流失败: license 不合法，调用失败")
            return
        }
        if (result == V2TXLiveCode.V2TXLIVE_OK){
            Log.d("TAG", "推流成功: ")
            mBinding.btCreateLive.visibility = View.GONE
            mBinding.clLive.visibility = View.VISIBLE
            initWebSocket()
        }

    }


    override fun onDestroy() {
        super.onDestroy()
        mPusher.stopCamera()
        mPusher.stopMicrophone()
        mPusher.stopPush()
        mPusher.release()
        //解除消息监听
        V2TIMManager.getMessageManager().removeAdvancedMsgListener(messageListener)
    }
}